package com.knowledgeBase.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSSClient;
import com.knowledgeBase.result.RestResponse;
import com.knowledgeBase.service.IOssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;

/**
 * @author 鲤鱼乡
 * date 2022年03月20日下午 3:29
 * info OssServiceImpl
 */
@Service
public class OssServiceImpl implements IOssService {
    private static final String[] imageExtension = {".jpg", ".jpeg", ".png", ".gif","svg"};
    private final OSSClient ossClient;
    @Value("${aliyun.oss.maxSize}")
    private int maxSize;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Value("${aliyun.oss.dir.prefix}")
    private String dirPrefix;

    public OssServiceImpl(OSSClient ossClient) {
        this.ossClient = ossClient;
    }

    /**
     * 根据图片链接将其上传到 OSS
     * param url
     */
    @Override
    public Serializable upload(String url) {
        String objectName = getFileName(url);
        try (InputStream inputStream = new URL(url).openStream()) {
            ossClient.putObject(bucketName, objectName, inputStream);
        } catch (IOException e) {
            return RestResponse.fail("根据外链上传图片到 OSS 出错了：");
        }
        return formatOSSPath(objectName);
    }

    private String getFileName(String url) {
        String ext = "";
        for (String extItem : imageExtension) {
            if (url.indexOf(extItem) != -1) {
                ext = extItem;
                break;
            }
        }
        if (StrUtil.hasEmpty(ext)) return "0";
        return dirPrefix + DateUtil.today() + "/" + IdUtil.randomUUID() + ext;
    }

    private String formatOSSPath(String objectName) {
        if (objectName.equals("0")) return null;
        return ("https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + objectName);
    }

    @Override
    public String upload(InputStream inputStream, String name) {
        String objectName = getFileName(name);
        // 创建PutObject请求。
        ossClient.putObject(bucketName, objectName, inputStream);
        return formatOSSPath(objectName);
    }

    @Override
    public String upload(MultipartFile file) {
        try {
            return upload(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            return String.valueOf(RestResponse.fail(e.getMessage()));
        }
    }


    @Override
    public String getEndPoint() {
        return ossClient.getEndpoint().getHost();
    }
}
